package com.tang.dict;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tang.system.vo.Result;
import com.tang.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.Map;

@Slf4j
public class BaseDictParser extends DictFieldParseAble {
    @Override
    protected Object parseDict(Object obj) {
        beforeParse();
        Object o = null;
        try {
            o = doParseDict(obj);
        } catch (Exception e) {
            afterException();
            log.error(e.getMessage(), e);
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        afterParse();
        return o;
    }

    protected void afterParse() {
        super.afterParse();
    }

    protected void beforeParse() {
        super.beforeParse();
    }

    @Override
    protected Object doParseDict(Object obj) {
        if (CommonUtils.isEmpty(obj)
                || obj.getClass().isPrimitive()
                || String.class.isAssignableFrom(obj.getClass())
                || obj.getClass().isAssignableFrom(String.class)
                || JSONObject.class.isAssignableFrom(obj.getClass())
                || JSONArray.class.isAssignableFrom(obj.getClass())
                || JSON.class.isAssignableFrom(obj.getClass())
                || Number.class.isAssignableFrom(obj.getClass())) {
            return obj;
        }

        if (obj instanceof Result)
            return parseResult((Result) obj);

        if (obj.getClass().isArray())
            return parseArray((Object[]) obj);

        if (Collection.class.isAssignableFrom(obj.getClass()))
            return parseCollection((Collection) obj);

        if (Map.class.isAssignableFrom(obj.getClass()))
            return parseMap((Map) obj);

        if (IPage.class.isAssignableFrom(obj.getClass()))
            return parseIPage((IPage) obj);

        return doParseObj(obj);
    }

    private Object doParseObj(Object obj) {
        JSONObject res = JSONObject.parseObject(JSONObject.toJSONString(obj));
        parseFields(obj, res);
        return res;
    }
}
